package com.lovely3x.jobservice.utils;

import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by lovely3x on 16-2-22.
 */
public class ArrayMap<K, V> implements Map<K, V> {

    private ArrayList<K> keySet = new ArrayList<>();
    private ArrayList<V> values = new ArrayList<>();


    @Override
    public void clear() {
        keySet.clear();
        values.clear();
    }

    @Override
    public boolean containsKey(Object key) {
        return keySet.contains(key);
    }

    @Override
    public boolean containsValue(Object value) {
        return values.contains(value);
    }

    @NonNull
    @Override
    public Set<Entry<K, V>> entrySet() {
        throw new UnsupportedOperationException();
    }

    @Override
    public V get(Object key) {
        int index = keySet.indexOf(key);
        if (index == -1) return null;
        return values.get(index);
    }

    @Override
    public boolean isEmpty() {
        return values.isEmpty();
    }

    @NonNull
    @Override
    public Set<K> keySet() {
        return new HashSet<>(keySet);
    }

    @Override
    public V put(K key, V value) {
        boolean addResult = keySet.add(key) && values.add(value);
        if (addResult) {
            return value;
        }
        return null;
    }

    public int indexOfKey(K k) {
        return keySet.indexOf(k);
    }

    public K getKey(int index) {
        return keySet.get(index);
    }

    public V getValue(int index) {
        return values.get(index);
    }


    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }
    }

    @Override
    public V remove(Object key) {
        int index = keySet.indexOf(key);
        if (index != -1) {
            keySet.remove(key);
            return values.remove(index);
        }
        return null;
    }

    @Override
    public int size() {
        return keySet.size();
    }

    @NonNull
    @Override
    public Collection<V> values() {
        return values;
    }

}
